package com.vivo.Utils;

import com.thinkgem.jeesite.common.utils.StringUtils;
import com.vivo.dingtalk.auth.AuthHelper;
import com.vivo.system.entity.VivoDingConf;
import com.vivo.system.service.VivoDingConfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class DingConfUtil {

    @Autowired
    private VivoDingConfService dingConfService;

    /**
     * 获取对应企业的accessToken
     * 1. 保存最新的到数据库中
     * 2. 如果超时自动获取新的
     * @param compId
     * @return
     */
    public String getAccessToken(String compId) {
        VivoDingConf dingConf = getDingConf(compId);

        return dingConf == null ? null : dingConf.getAccessToken();
    }


    public VivoDingConf getDingConf(String compId) {
        VivoDingConf vivoDingConf = dingConfService.getByComp(compId);

        // 获取access_token
        String accessToken = null;
        String ticket = null;

        long cacheTime = 1000 * 60 * 55 * 2;
        long curTime = System.currentTimeMillis();

        if (StringUtils.isBlank(vivoDingConf.getAccessToken()) ||
                vivoDingConf.getAccTokenTime() == null ||
                curTime - vivoDingConf.getAccTokenTime().getTime() >= cacheTime) {
            try {
                accessToken = AuthHelper.getAccessToken(vivoDingConf.getCorpId(), vivoDingConf.getCorpSecret());
                ticket = AuthHelper.getJsapiTicket(accessToken);
            }catch (Exception e) {
                e.printStackTrace();
            }

            if (accessToken != null && ticket != null) {
                vivoDingConf.setAccessToken(accessToken);
                vivoDingConf.setAccTokenTime(new Date());
                vivoDingConf.setTicket(ticket);
                vivoDingConf.setTicketTime(new Date());

                dingConfService.save(vivoDingConf);
            }
        }

        return vivoDingConf;
    }
}
